<!--
  * 库位列表
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="4">
          <a-form-item label="品牌" class="smart-margin-bottom0">
            <BrandSelect v-model:value="queryForm.company_brand_id" placeholder="品牌" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="商品名称" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.goods_name" placeholder="商品名称" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="商品编码" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.no" placeholder="商品编码" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="分类" class="smart-margin-bottom0">
            <CateSelect v-model:value="queryForm.company_cate_id" placeholder="分类" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="onExport" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns.filter((item) => !item.disabled)" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ fixed: true }" :showExpandColumn="false" expandRowByClick>
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'goods_name'">
            <CopyText :text="text">
              {{ text }}
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'img'">
            <div class="smart-table-operate">
              <a-image :width="30" :src="text === '' ? faillImg : text" />
            </div>
          </template>
          <template v-if="['totalAvailableQuantities', 'totalWarehouseQuantities'].includes(column.dataIndex)">
            {{ text === '' ? 0 : text }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click.stop="detail(record, currentWarehouse.id)" type="link" v-privilege="'goods:update'">库存变化</a-button>
            </div>
          </template>
        </template>
        <template #expandedRowRender="{ record }">
          <div class="content">
            <div class="parent" v-for="item in record.batches" :key="item.code">
              <div class="div1">批次：{{ dayjs(item.batch_time).format('YYYY-MM-DD') }}</div>
              <div class="div2">数量：{{ transformSpec(item.quantity, record.spec) }}</div>
              <div class="div3">仓库：{{ item.warehouse_name }}</div>
              <div class="div3">库位：{{ item.code }}</div>
            </div>
          </div>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell>总计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell v-if="currentWarehouse.warehouse_type === 1">
                <a-typography-text type="danger">{{ totalData.total_pre_num || '' }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ totalData.total_num || '' }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ Number(totalData.total_agree_amount).toFixed(2) || '' }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <!---------- 详情 begin ----------->
    <InventoryDetailsModal ref="detailRef" @reload-list="queryData" />
    <!---------- 详情 end ----------->
  </a-card>
</template>
<script setup lang="ts">
import dayjs from 'dayjs'
import InventoryDetailsModal from './components/inventory-details-modal.vue'
import { inventoryApi, warehouseApi } from '@/api/business/storage/warehouse-api'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import CateSelect from '@/components/business/select/cate-select.vue'
import BrandSelect from '@/components/business/select/brand-select.vue'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useQuery } from '@/hooks/web/use-query-hook'
import { useResize } from '@/hooks/web/use-resize-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import eventEmitter from '@/lib/event-emitter'
import faillImg from '@/assets/images/notice/failImg.png'
import { useTransformSpec } from '@/hooks/web/use-transform-spec'
import { useEnums } from '@/hooks/plugins/useEnums'
const { transformSpec } = useTransformSpec()
const { getDescByValue } = useEnums()
// ---------------------------- 表格列 ----------------------------
const currentWarehouse = ref({
  id: undefined,
  warehouse_type: 1
})

const columns = computed(() => {
  return [
    {
      title: '图片',
      dataIndex: 'img',
      width: 40
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 200
    },
    {
      title: '商品编码',
      dataIndex: 'no'
    },
    {
      title: '品牌',
      dataIndex: ['brand', 'brand_name']
    },
    {
      title: '分类',
      dataIndex: ['cate', 'cate_name']
    },
    {
      title: '可售库存',
      dataIndex: 'totalAvailableQuantities',
      width: 150,
      disabled: currentWarehouse.value.warehouse_type === 2
    },
    {
      title: '实际库存',
      dataIndex: 'totalWarehouseQuantities',
      width: 150
    },
    {
      title: '货值金额',
      dataIndex: 'totalAgreeAmount',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 150
    }
  ].filter((item) => !item.disabled)
})

// ---------------------------- 查询数据表单和方法 ----------------------------
// 聚合同批次、库位的库存批次数据并换算成可读格式
const formatInventoryBatches = (inventoryBatches: any[]) => {
  const list = new Map()
  for (const item of inventoryBatches) {
    if (item.quantity === 0) continue
    const time = dayjs(item.batch_time).format('YYYY-MM-DD').valueOf()
    const key = `${time}${item?.warehouse_location_id ? `-${item.warehouse_location_id}` : ''}`
    // 将仓库位置的code数组转换为逗号分隔的字符串
    const locationCodes = item.location ? item.location.map((location: any) => location.code).join('| ') : ''
    const value = {
      batch_time: time,
      code: locationCodes,
      // code: `${item.location?.code ?? '-'}`,
      warehouse_name: `${item.warehouse?.name}(${getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item.warehouse?.attribute_type)})`,
      quantity: item.quantity
    }
    if (list.has(key)) {
      const temp = list.get(key)
      temp.quantity += value.quantity
      // 合并code
      const existingCodes = temp.code.split(', ').map((code) => code.trim())
      const newCodes = value.code.split(', ').map((code) => code.trim())
      const combinedCodes = [...new Set([...existingCodes, ...newCodes])].join(', ') // 去重并合并
      temp.code = combinedCodes

      list.set(key, temp)
    } else {
      list.set(key, value)
    }
  }
  return Array.from(list.values()).sort((a, b) => b.batch_time - a.batch_time)
}
// 总计
const totalData = ref({})

const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, setQuery } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      id: unref(currentWarehouse).id || ''
    }
    const res = await inventoryApi.queryList(data)
    const list = res.data.data.map((item) => {
      return {
        ...item,
        batches: formatInventoryBatches(item.batches)
      }
    })
    let resp = await warehouseApi.listAmount(data)
    totalData.value = resp.data
    return {
      list,
      total: res.data.total
    }
  },
  queryFormFilter: {
    goods_name: '',
    no: '',
    company_brand_id: undefined,
    company_cate_id: undefined
  },
  queryFormOp: {
    goods_name: QUERY_FORM_OP['模糊查询'],
    no: QUERY_FORM_OP['模糊查询'],
    company_brand_id: QUERY_FORM_OP['全等查询'],
    company_cate_id: QUERY_FORM_OP['全等查询']
  }
})

eventEmitter.on('Custom:queryInventoryList', (params) => {
  currentWarehouse.value = Object.assign(currentWarehouse.value, params)
  onSearch()
})

// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData, id) => {
  detailRef.value.showDrawer(goodsData, id)
}
// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const filter = {
    goods_name: queryForm.value.goods_name,
    no: queryForm.value.no,
    company_brand_id: queryForm.value.company_brand_id,
    company_cate_id: queryForm.value.company_cate_id
  }
  const op = {
    goods_name: QUERY_FORM_OP['模糊查询'],
    no: QUERY_FORM_OP['模糊查询'],
    company_brand_id: QUERY_FORM_OP['全等查询'],
    company_cate_id: QUERY_FORM_OP['全等查询']
  }
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(op),
    id: unref(currentWarehouse).id
  }
  inventoryApi.exportXlsx(data)
}
</script>
<style lang="less" scoped>
:deep(.ant-table-expanded-row .ant-table-cell) {
  background-color: #e6f4ff;
}
:deep(.ant-table-expanded-row .ant-table-cell:hover) {
  background-color: #e6f4ff;
}
.content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.parent {
  // margin-left: 45%;
  // margin-right: 5%;
  display: grid;
  grid-template-columns: 20% 25% 25% 30%;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.parent:last-of-type {
  border-bottom: none;
}

.div3 {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本 */
  width: 100%; /* 设置一个宽度限制，以便文本超出时能看到效果 */
}
</style>
